//
//  XFoundSearchViewController.m
//  Bees
//
//  Created by Xiaohan on 2018/12/20.
//  Copyright © 2018 xiaohan. All rights reserved.
//

#import "XFoundSearchViewController.h"
#import "FFTagsView.h"
#import "XHomeItemCell.h"
#import "FoundServer.h"
#import "ScatterDappManager.h"
#import "AllCommunityTableCell.h"
#import "ChatServer.h"
#import "XHSessionViewController.h"
#import "PCScatterViewController.h"
#define kSearchHeadHeight AdaptedWidth(50.0f)
@interface XFoundSearchViewController ()<UITextFieldDelegate>
@property (nonatomic,strong) UITextField *searchTF;
@property (nonatomic,strong) UIScrollView *contentView;
@property (nonatomic,strong) FFTagsView *historyTagView;
@property (nonatomic,strong) FFTagsView *hotTagView;
@property (strong, nonatomic) FFTagsViewConfig *config;
@property (strong, nonatomic) UIView *historyHeadView;
@property (strong, nonatomic) UIView *hotHeadView;
@property (assign, nonatomic) FoundSearchType type;
@property (strong, nonatomic) FoundServer *foundServer;
@property (strong, nonatomic) ChatServer *chatServer;
@end

@implementation XFoundSearchViewController
- (instancetype)initWithType:(FoundSearchType)Type{
    if (self == [super init]) {
        self = [super initWithStyle:UITableViewStylePlain];
        self.type = Type;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    if (self.type == FoundSearchTypeDapp) {
        [self getHotDappData];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self gethistoryData];
    [self.tableView reloadData];
}


- (void)loadMore:(BOOL)isMore{
    if (self.type == FoundSearchTypeDapp) {
        [self.foundServer getDappListIsMore:isMore completion:^(BOOL success, BOOL isHaveNextPage, NSString * _Nonnull msg) {
            [self endHeaderFooterRefreshingIsHaveNextPage:isHaveNextPage];
            if (success) {
                [self.tableView reloadData];
            }else{
                [self.view makeToast:msg];
            }
        }];
    }else{
        [self.chatServer getSearchChatroomListIsMore:isMore completion:^(BOOL success, BOOL isHaveNextPage, NSString * _Nonnull msg) {
            [self endHeaderFooterRefreshingIsHaveNextPage:isHaveNextPage];
            if (success) {
                [self.tableView reloadData];
            }else{
                [self.view makeToast:msg];
            }
        }];
    }
}
#pragma mark - action
- (void)beginSearch:(NSString*)key{
  
    if (key.length) {
        self.contentView.hidden = YES;
    }else{
        self.contentView.hidden = NO;
        if (self.type == FoundSearchTypeDapp) {
            [self.foundServer.dappList removeAllObjects];
        }else{
            [self.chatServer.chatList removeAllObjects];
        }
        [self.tableView reloadData];
        [self gethistoryData];
        return;
    }
    if (self.type == FoundSearchTypeDapp) {
//        [kUserManager saveSeachWord:key];
        self.foundServer.dappKey = key;
        [self loadMore:NO];
    }else{
//        [kUserManager saveGroupSeachWord:key];
        self.chatServer.searchKey = key;
        [self loadMore:NO];
    }
}

- (void)gethistoryData{
    NSArray *tags;
    if (self.type == FoundSearchTypeDapp) {
        tags = [kUserManager haveSearchWords];
    }else{
        tags = [kUserManager haveGroupSearchWords];
    }
    if (self.historyTagView) {
        [self.historyTagView removeFromSuperview];
        self.historyTagView = nil;
    }
    if (tags.count) {
        self.historyHeadView.hidden = NO;
        self.historyHeadView.height = kSearchHeadHeight;
        self.historyTagView = [[FFTagsView alloc]initWithFrame:CGRectMake(0, self.historyHeadView.height, self.contentView.width, 1.0f) tagsArray:tags config:self.config];
        [self.contentView addSubview:self.historyTagView];
        kWeakSelf(self);
        self.historyTagView.tagBtnClickedBlock = ^(FFTagsView *aTagsView, UIButton *sender, NSInteger tag) {
            if (self.type == FoundSearchTypeDapp) {
                [kUserManager saveSeachWord:sender.titleLabel.text];
            }else{
                [kUserManager saveGroupSeachWord:sender.titleLabel.text];
            }
            weakself.searchTF.text = sender.titleLabel.text;
            NSString* key = [weakself.searchTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];;
            if (key.length && [RegularExp isUrlAddress:key]) {
                [weakself jumpWeb:key];
            }
            [weakself beginSearch:key];
        };
        
    }else{
        self.historyHeadView.hidden = YES;
        self.historyHeadView.height = 0.01f;
    }
    self.hotHeadView.top = self.historyTagView.bottom;
    self.hotTagView.top = self.hotHeadView.bottom;
    self.contentView.contentSize = CGSizeMake(0, self.historyTagView.height+self.hotTagView.height+4*kSearchHeadHeight);
}
- (void)jumpWeb:(NSString*)key{
    kWeakSelf(self);
    if (key.length && [RegularExp isUrlAddress:key]) {
        [XAlertTool alertTitle:XLocalized(@"温馨提示") message:[NSString stringWithFormat:@"%@%@",XLocalized(@"是否前往"),key] cancelAction:^{
            
        } sureAction:^{
            DappInfo *info = [DappInfo new];
            NSString *keys = key;
            if (![key hasPrefix:@"http://"]&&![key hasPrefix:@"https://"]) {
                keys = [NSString stringWithFormat:@"http://%@",keys];
            }
            info.address = keys;
            info.title = key;
            info.dappId =key;
            info.imgUrl =@"";
            PCScatterViewController *vc = [PCScatterViewController new];
            vc.dappInfo = info;
            [weakself.navigationController pushViewController:vc animated:YES];
        }];
        return;
    }
}
- (void)getHotDappData{
    [self.foundServer getHotSearchDappListCompletion:^(BOOL success, NSString * _Nonnull msg) {
        if (success) {
            NSMutableArray *names = [NSMutableArray array];
            [self.foundServer.hotSearchList enumerateObjectsUsingBlock:^(FoundRecommendModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [names addObject:obj.name];
            }];
            if (self.hotTagView) {
                [self.hotTagView removeFromSuperview];
                self.hotTagView = nil;
            }
            self.hotHeadView.top = self.historyTagView.bottom;
            self.hotTagView = [[FFTagsView alloc]initWithFrame:CGRectMake(0, self.hotHeadView.bottom, self.contentView.width, 1.0f) tagsArray:names config:self.config];
            [self.contentView addSubview:self.hotTagView];
            kWeakSelf(self);
            self.hotTagView.tagBtnClickedBlock = ^(FFTagsView *aTagsView, UIButton *sender, NSInteger tag) {
                if (self.type == FoundSearchTypeDapp) {
                    [kUserManager saveSeachWord:sender.titleLabel.text];
                }else{
                    [kUserManager saveGroupSeachWord:sender.titleLabel.text];
                }
                weakself.searchTF.text = sender.titleLabel.text;
                NSString* key = [weakself.searchTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];;
                if (key.length && [RegularExp isUrlAddress:key]) {
                    [weakself jumpWeb:key];
                }
                [weakself beginSearch:key];
            };
            self.contentView.contentSize = CGSizeMake(0, self.historyTagView.height+self.hotTagView.height+4*kSearchHeadHeight);
        }else{
            [self.view makeToast:msg];
        }
    }];
   
}

- (void)setupUI{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth-70, 44)];
    UIButton *searchBtn = [[UIButton alloc]initWithFrame:CGRectMake(titleView.width-35, 4.5, 35, 35)];
    [searchBtn setImage:IMAGE_NAMED(@"search") forState:UIControlStateNormal];
    [titleView addSubview:searchBtn];
    UIView*line = [[UIView alloc]initWithFrame:CGRectMake(0, titleView.height-CGFloatFromPixel(1.0f), titleView.width, CGFloatFromPixel(1.0f))];
    line.backgroundColor = UIColorHex(#FFCC03);
    [titleView addSubview:line];
    
    self.searchTF = [[UITextField alloc]initWithFrame:CGRectMake(0, 0, titleView.width-searchBtn.width, titleView.height-line.height)];
    self.searchTF.delegate = self;
    self.searchTF.backgroundColor = UIColor.whiteColor;
    [titleView addSubview:self.searchTF];
    self.searchTF.placeholder = XLocalized(@"搜索内容");
    self.searchTF.textColor = UIColorHex(333333);
    self.searchTF.returnKeyType = UIReturnKeySearch;
    [self.searchTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.navigationItem.titleView = titleView;
    
    self.contentView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.customNavigationBar.height, self.view.width, self.view.height - self.customNavigationBar.height)];
    self.contentView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:self.contentView];
    
    self.historyHeadView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.contentView.width, kSearchHeadHeight)];
    [self.contentView addSubview:self.historyHeadView];
    UILabel *hisTitleLab = [[UILabel alloc]initWithFrame:CGRectMake(kNormalSpace, AdaptedWidth(30), 100,  AdaptedWidth(20))];
    hisTitleLab.textColor = UIColorHex(#FFBB03);
    hisTitleLab.text = @"历史搜索";
    hisTitleLab.font = kBoldFont(16);
    [self.historyHeadView addSubview:hisTitleLab];
    
    if (self.type == FoundSearchTypeDapp) {
        self.hotHeadView = [[UIView alloc]initWithFrame:CGRectMake(0, self.historyTagView.height, self.contentView.width, kSearchHeadHeight)];
        [self.contentView addSubview:self.hotHeadView];
        UILabel *hotTitleLab = [[UILabel alloc]initWithFrame:CGRectMake(kNormalSpace, AdaptedWidth(30), 100, AdaptedWidth(20))];
        hotTitleLab.textColor = UIColorHex(#FFBB03);
        hotTitleLab.text = @"热门搜索";
        hotTitleLab.font = kBoldFont(16);
        [self.hotHeadView addSubview:hotTitleLab];
    }
    
    UIButton *clearBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.historyHeadView.width-50, AdaptedWidth(30), 40, AdaptedWidth(30))];
    [clearBtn setTitle:@"清空" forState:UIControlStateNormal];
    [clearBtn setTitleColor:kColorTextGray forState:UIControlStateNormal];
    clearBtn.titleLabel.font = kDefaultFont(15);
    [self.historyHeadView addSubview:clearBtn];
    
    kWeakSelf(self);
    [searchBtn addTapBlock:^(UIButton * _Nonnull btn) {
        NSString* key = [weakself.searchTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];;
        if (key.length && [RegularExp isUrlAddress:key]) {
            [weakself jumpWeb:key];
        }
        [weakself beginSearch:key];
    }];
    
    [clearBtn addTapBlock:^(UIButton * _Nonnull btn) {
        DLog(@"清空");
        [XAlertTool alertTitle:@"清除搜索记录?" message:nil cancelAction:^{
            
        } sureAction:^{
            if (self.type == FoundSearchTypeDapp) {
                [kUserManager clearSearchWords];
                [weakself gethistoryData];
            }else{
                [kUserManager clearGroupSearchWords];
                [weakself gethistoryData];
            }
        }];
    }];
    
    self.tableView.tableFooterView = [UIView new];
    self.tableView.rowHeight = AdaptedWidth(83);
}
#pragma mark extField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSString* key = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];;
    if (key.length && [RegularExp isUrlAddress:key]) {
        [self jumpWeb:key];
    }else{
        [self beginSearch:key];
    }
    [textField resignFirstResponder];
    return YES;
}
- (void)textFieldDidChange:(UITextField *)textField{
    NSString* key = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];;
//    if (key.length && [RegularExp isUrlAddress:key]) {
//        [self jumpWeb:key];
//    }
    [self beginSearch:key];
}
#pragma mark - table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.type == FoundSearchTypeDapp) {
        return self.foundServer.dappList.count;
    }
    return self.chatServer.chatList.count;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.type == FoundSearchTypeDapp) {
        XHomeItemCell *itemCell = [XHomeItemCell cellForTableView:tableView];
        itemCell.model = self.foundServer.dappList[indexPath.row];
        return itemCell;
    }else{
        AllCommunityTableCell *chatCell = [AllCommunityTableCell cellForTableView:tableView];
        chatCell.model = self.chatServer.chatList[indexPath.row];
        kWeakSelf(self);
        chatCell.jionBtnClickBlock = ^(ChatroomModel*model) {
            
            if([[NIMSDK sharedSDK].teamManager isMyTeam:model.room_id]){
                XHSessionViewController *session = [[XHSessionViewController alloc]initWithSession:[NIMSession session:model.room_id type:NIMSessionTypeTeam]];
                [weakself.navigationController pushViewController:session animated:YES];
                return;
            }
            [XAlertTool alertTitle:[NSString stringWithFormat:@"%@”%@“?",XLocalized(@"加入群聊"),model.name] message:nil cancelAction:^{
                
            } sureAction:^{
                [weakself.chatServer joinChatroom:model.room_id completion:^(BOOL success, NSString * _Nonnull msg) {
                    if (success) {
                        model.is_join = YES;
//                        [[NIMSDK sharedSDK].teamManager applyToTeam:model.room_id message:@"" completion:^(NSError * _Nullable error, NIMTeamApplyStatus applyStatus) {
//                            if (!error ) {
                                XHSessionViewController *session = [[XHSessionViewController alloc]initWithSession:[NIMSession session:model.room_id type:NIMSessionTypeTeam]];
                                [weakself.navigationController pushViewController:session animated:YES];
//                            }else{
//                                [weakself.view makeToast:error.description];
//                            }
//                        }];
                    }else{
                        [weakself.view makeToast:msg];
                    }
                }];
            }];
        };
        return chatCell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.type == FoundSearchTypeDapp) {
        if (self.searchTF.text) {
            [kUserManager saveSeachWord:self.searchTF.text];
        }
    }else{
        if (self.searchTF.text) {
            [kUserManager saveGroupSeachWord:self.searchTF.text];
        }
    }
    if (self.type == FoundSearchTypeDapp) {
        [ScatterDappManager manager:self forDapp:self.foundServer.dappList[indexPath.row]];
        [self.foundServer postHotSearchDappId:self.foundServer.dappList[indexPath.row].modelId completion:^(BOOL success, NSString * _Nonnull msg) {
        }];
    }else{
        
    }
}
#pragma mark - getter

- (FFTagsViewConfig*)config{
    if (!_config) {
        _config = [[FFTagsViewConfig alloc] init];
        _config.itemHeight = AdaptedWidth(23.0f);
        _config.itemHerMargin = AdaptedWidth(14.0f);
        _config.itemVerMargin = AdaptedWidth(10.0f);;
        _config.topBottomSpace = AdaptedWidth(13.0f);
        _config.itemContentEdgs = kNormalSpace;
        _config.isCanSelected = YES;
        _config.hasBorder = YES;
        _config.borderRadius =  AdaptedWidth(23.0f)*.5;
        _config.normalBgImage = [UIImage imageWithColor:[UIColor colorWithHexString:@"#F7F7F7"]];
        _config.selectedTitleColor = UIColorHex(#999999);
        _config.fontSize = 12;
    }
    return _config;
}
- (FoundServer*)foundServer{
    if (!_foundServer) {
        _foundServer = [FoundServer new];
    }
    return _foundServer;
}
- (ChatServer*)chatServer{
    if (!_chatServer) {
        _chatServer = [ChatServer new];
    }
    return _chatServer;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
